package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import util.IdWorker;

import java.util.Date;
import java.util.List;

/**
 * Created by WF on 2020/3/31 15:33
 */
@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    //1.查询所有吐槽列表
    public List<Spit> findAll() {
        return spitDao.findAll();
    }
    //2.查询单个吐槽
    public Spit findOne(String spitId) {
       return spitDao.findById(spitId).get();
    }
    //3.添加吐槽
    public void insert(Spit spit) {
        //为其指定id
        spit.set_id(idWorker.nextId() + "");
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        spit.setPublishtime(new Date());
        spit.setParentid("0");
        spitDao.save(spit);
    }
    //4.修改吐槽
    public void update(Spit spit) {
        spitDao.save(spit);
    }
    //5.删除吐槽
    public void delete(String spitId) {
        spitDao.deleteById(spitId);
    }
    //6.根据上维id查询
    public PageResult comment(String parentid, int page, int size) {
        //6.1)根据父id查询分页结果
        Page<Spit> spitPage = spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
        //6.2)返回自己的分页结果
        return new PageResult(spitPage.getTotalElements(),spitPage.getContent());
    }
    //7.吐槽点赞(方法一：使用传统方法)--效率不太高
    public void thumbup(String spitId) {
        Spit one = findOne(spitId);
        one.setThumbup(one.getThumbup()+1);
        spitDao.save(one);
    }
    //8.吐槽点赞（方法二：使用mongodb的模板完成）
    public void thumbup2(String spitId) {
        //8.1)定义查询条件
        Query query = new Query();
        Criteria criteria = new Criteria("_id").is(spitId);
        query.addCriteria(criteria);
        //8.2)定义要修改的对象
        Update update = new Update();
        update.inc("thumbup",1);
        //8.3）修改吐槽
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
